<template>
  <div
    id="flexContainer"
    ref="flexContainer"
    @dragover.prevent="handleContainerDragOver"
    @drop="handleDrop"
  >
    <!-- ghost 列前置插入 -->
    <div v-if="ghostColPosition === 'left'" class="ghost-col"></div>

    <div
      v-for="(colItems, colIndex) in items"
      :key="colIndex"
      class="drag-col"
      @dragover.prevent="handleDragOver(colIndex, null)"
    >
      <div
        v-for="(item, itemIndex) in colItems"
        :key="item.id"
        class="drag-item"
        draggable="true"
        @dragstart="handleDragStart(colIndex, itemIndex, item)"
        @dragover.prevent="(e) => handleDragOver(e, colIndex, itemIndex, $event.currentTarget)"
        @dragend="handleDragEnd"
        :class="{ dragging: isDragging && dragItem.id === item.id }"
      >
        {{ item.name }}
      </div>
    </div>

    <!-- ghost 列后置插入 -->
    <div v-if="ghostColPosition === 'right'" class="ghost-col"></div>
  </div>
</template>

<script>
import { generateRandomItem } from "../assets/utils";

export default {
  name: "dragAndDrop",
  data() {
    return {
      items: [generateRandomItem(1), generateRandomItem(2), generateRandomItem(3)],
      dragItem: null,
      dragFromCol: null,
      dragFromIndex: null,
      isDragging: false,
      dragOverTimer: null, // 防抖计时器
      ghostColPosition: null, // 'left' | 'right' | null
      dragOverTimer: null,
    };
  },
  methods: {

    handleDragStart(colIndex, itemIndex, item) {
      this.dragItem = item;
      this.dragFromCol = colIndex;
      this.dragFromIndex = itemIndex;
      this.isDragging = true;
    },

    handleDragOver(event, targetCol, targetIndex, el) {
      if (!this.dragItem || targetCol === null || targetIndex === null) return;

      // 计算鼠标位置相对目标元素的位置
      const targetRect = el.getBoundingClientRect();
      const mouseY = event.clientY;
      const targetMiddleY = targetRect.top + targetRect.height / 2;

      // 根据鼠标位置判断插入位置：向下 -> 上方，向上 -> 下方
      let insertIndex = targetIndex;
      if (mouseY > targetMiddleY) {
        insertIndex += 1;
      }

      // 如果拖入的是原始位置，不处理（注意 insertIndex 的判断）
      if (
        targetCol === this.dragFromCol &&
        (insertIndex === this.dragFromIndex || insertIndex === this.dragFromIndex + 1)
      ) {
        return;
      }

      // 从原位置移除
      const fromColItems = [...this.items[this.dragFromCol]];
      fromColItems.splice(this.dragFromIndex, 1);
      this.$set(this.items, this.dragFromCol, fromColItems);

      // 处理插入位置的偏移（如果是同列往后插入，需要调整 index）
      let adjustedInsertIndex = insertIndex;
      if (
        targetCol === this.dragFromCol &&
        insertIndex > this.dragFromIndex
      ) {
        adjustedInsertIndex -= 1;
      }

      // 插入到新位置
      const toColItems = [...this.items[targetCol]];
      toColItems.splice(adjustedInsertIndex, 0, this.dragItem);
      this.$set(this.items, targetCol, toColItems);

      // 更新拖拽位置信息
      this.dragFromCol = targetCol;
      this.dragFromIndex = adjustedInsertIndex;
    },

    handleDrop() {
      if (this.ghostColPosition === "left") {
        this.items.unshift([]);

        // ⚠️ 插入新列后，原列索引偏移
        if (this.dragFromCol !== null) {
          this.dragFromCol += 1;
        }

        // 插入后立即将拖拽项插入新列中
        const toColItems = [...this.items[0]];
        toColItems.push(this.dragItem);
        this.$set(this.items, 0, toColItems);
        this.dragFromCol = 0;
        this.dragFromIndex = toColItems.length - 1;
      } else if (this.ghostColPosition === "right") {
        this.items.push([]);

        const newColIndex = this.items.length - 1;
        const toColItems = [...this.items[newColIndex]];
        toColItems.push(this.dragItem);
        this.$set(this.items, newColIndex, toColItems);
        this.dragFromCol = newColIndex;
        this.dragFromIndex = toColItems.length - 1;
      }

      this.cleanupDragState();
    },



    handleDragEnd() {
      this.cleanupDragState();
    },

    cleanupDragState() {
      this.dragItem = null;
      this.dragFromCol = null;
      this.dragFromIndex = null;
      this.isDragging = false;
      this.ghostColPosition = null;
    },

    handleContainerDragOver(e) {
      const container = this.$refs.flexContainer;
      const rect = container.getBoundingClientRect();
      const offsetX = e.clientX - rect.left;
      const offsetY = e.clientY - rect.top;

      const nearTop = offsetY < 50;
      const nearLeft = offsetX < 50;
      const nearRight = rect.width - offsetX < 50;

      if (nearTop && nearLeft) {
        this.ghostColPosition = "left";
      } else if (nearTop && nearRight) {
        this.ghostColPosition = "right";
      } else {
        this.ghostColPosition = null;
      }
    },

    throttleAddColumn(position) {
      if (this.dragOverTimer) return;

      this.dragOverTimer = setTimeout(() => {
        const newCol = [];
        if (position === "left") {
          this.items.unshift(newCol);
        } else if (position === "right") {
          this.items.push(newCol);
        }
        this.dragOverTimer = null;
      }, 500); // 防抖，避免狂加列
    },
  },
};
</script>

<style scoped>
#flexContainer {
  display: flex;
  gap: 20px;
}

.drag-col {
  flex: 1;
  /* 平均分配空间 */
  min-width: 200px;
  /* 最小宽度限制，防止列太窄 */
  min-height: 300px;
  border: 1px solid #ccc;
  background: #f5f5f5;
  padding: 10px;
  box-sizing: border-box;
}

.drag-item {
  background: antiquewhite;
  margin: 10px 0;
  padding: 20px;
  word-break: break-word;
  border-radius: 6px;
  transition: transform 0.2s ease;
}

.drag-item.dragging {
  opacity: 0.6;
  transform: scale(1.03);
  background: #ffddb3;
}

.ghost-col {
  flex: 1;
  min-width: 200px;
  min-height: 300px;
  border: 2px dashed #999;
  background-color: rgba(200, 200, 200, 0.1);
  box-sizing: border-box;
  margin: 0 5px;
}
</style>
